package com.woniuxy.commons.utils;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;

/**
 * @Auther: 王敞
 * @E-mail： 365799712@qq.com
 * @Date: 2020/07/29/10:55
 * @Description:
 */
@Component
public class JwtUtil {
    public static final String SECRET_KEY = "123456";// 秘钥
    public static final long TOKEN_EXPRE_TIME = 1000 * 60 * 60;// token的过期时间
    public static final long REFRESH_TOKEN_EXPRE_TIME = 1000 * 60 * 60 * 24;// refreshtoken的过期时间
    public static final String ISSUSER = "wangchang";// 令牌的签发人

    public static final int STATUS_SUCCESS = 1;
    public static final int STATUS_EXPIRE = 0;
    public static final int STATUS_ERROR = -1;

    // 生成token
    public static String makeToken(String uname) {
        // 生成签发时间
        Date date = new Date();
        // 生成签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        // 生成token
        String token = JWT.create().withIssuer(ISSUSER) // 指定签发人
                .withIssuedAt(date) // 签发时间
                .withExpiresAt(new Date(date.getTime() + TOKEN_EXPRE_TIME)) // 过期时间
                .withClaim("uname", uname) // 用户账号
                .sign(algorithm);
        return token;
    }

    // 校验token
    public static int validate(String token) {
        try {
            // 创建加密算法对象
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            // 生成校验器
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUSER).build();
            verifier.verify(token);
            // 合法
            return STATUS_SUCCESS;
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            return STATUS_EXPIRE;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return STATUS_ERROR;
    }

    // 从token中提取uname
    public static String getUname(String token) {
        try {
            return JWT.decode(token).getClaim("uname").asString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
